import 'package:dio/dio.dart';
import 'package:leader_help/utils/httputils/responseinterceptor.dart';
import 'package:leader_help/utils/httputils/resultdata.dart';
import 'package:leader_help/utils/httputils/topdiointerceptor.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'urlpath.dart';

class HttpManager {
  static HttpManager _instance = HttpManager._internal();
  late Dio _dio;

  static const CODE_SUCCESS = 200;
  static const CODE_TIME_OUT = -1;
  static const CONNECT_TIMEOUT = 15000;

  factory HttpManager() => _instance;

  ///通用全局单例，第一次使用时初始化
  HttpManager._internal() {
    _dio = Dio(BaseOptions(
      baseUrl: UrlPath.baseUrl,
      connectTimeout: CONNECT_TIMEOUT,
    ));
    _dio.interceptors.add(TopDioIntercepter());
    _dio.interceptors.add(ResponseInterceptors());
  }

  static HttpManager getInstance({String? baseUrl}) {
    if (baseUrl == null) {
      return _instance._normal();
    } else {
      return _instance._baseUrl(baseUrl);
    }
  }

  //用于指定特定域名
  HttpManager _baseUrl(String baseUrl) {
    if (_dio != null) {
      _dio.options.baseUrl = baseUrl;
    }
    return this;
  }

  //一般请求，默认域名
  HttpManager _normal() {
    if (_dio != null) {
      if (_dio.options.baseUrl != UrlPath.baseUrl) {
        _dio.options.baseUrl = UrlPath.baseUrl;
      }
    }
    return this;
  }

  ///通用的GET请求
  get(api, {params, withLoading = true}) async {
    if (withLoading) {
      EasyLoading.show();
    }

    Response response;

    response = await _dio.get(api, queryParameters: params);

    return response.data;
  }

  ///通用的POST请求
  post(api, {params, withLoading = true}) async {
    if (withLoading) {
      EasyLoading.show();
    }

    Response response;

    response = await _dio.post(api, data: params);

    return response.data;
  }

  //上传文件

  uploadFiles(api,
      {required List<MultipartFile> multipartFiles, withLoading = true}) async {
    FormData formData = FormData.fromMap({'files': multipartFiles});

    Response response = await HttpManager()._dio.post(api, data: formData,
        onSendProgress: (int sent, int total) {
      EasyLoading.showProgress(sent / total, status: '上传中...');
    });

    EasyLoading.dismiss();

    return response;
  }
}

ResultData resultError(DioError e) {
  Response errorResponse;
  if (e.response != null) {
    errorResponse = e.response!;
  } else {
    errorResponse =
        Response(statusCode: 666, requestOptions: RequestOptions(path: ''));
  }
  if (e.type == DioErrorType.connectTimeout ||
      e.type == DioErrorType.receiveTimeout) {
    errorResponse.statusCode = HttpManager.CODE_TIME_OUT;
  }
  return ResultData(
      errorResponse.statusMessage, false, errorResponse.statusCode!);
}
